package newcrunch.gui.tree;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JEditorPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.plaf.metal.MetalTreeUI;
import javax.swing.text.JTextComponent;
import javax.swing.tree.DefaultTreeModel;
import jsyntaxpane.actions.ActionUtils;
import newcrunch.util.DisplayHelper;

/**
 * @author WL
 */
public class CustomTree extends JTree
{
    private TreeBuilder treeBuilder;
    public static final int TREE_COOLDOWN = 50;
    
    public CustomTree()
    {
        setUI(new MetalTreeUI());
        setRootVisible(false);
        setShowsRootHandles(true);
        treeBuilder = new TreeBuilder();
        putClientProperty("JTree.lineStyle", "Angled");
        setCellRenderer(new TreeCellDisplay());
        ToolTipManager.sharedInstance().registerComponent(this); //for tool tips to be displayed
    }
    
    /**
     * Go to the line of the editor which has the declaration of the node.
     * @param component
     * @param node 
     */
    public void goToLine(JTextComponent component, CustomTreeNode node)
    {
        ActionUtils.setCaretPosition(component, node.getLineNumber(), 0);
        DisplayHelper.centerLineInScrollPane(component);
    }
    
    public void regenerateTree(final String text)
    {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                //update the jtree view
                setModel(new DefaultTreeModel(treeBuilder.generateTree(text)));

                //expands all nodes
                for (int i = 0; i < getRowCount(); i++)
                    expandRow(i);

                //refresh the display
                repaint();       
            }
        });
    }
    
    public void configureMouseListeners(final JEditorPane editor)
    {
        addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt)
            {
                CustomTreeNode target = (CustomTreeNode)getLastSelectedPathComponent();
                //left click to focus on instance declaration
                if (target != null && evt.getButton() == MouseEvent.BUTTON1)
                    goToLine(editor, target);
            }
        });
    }
}
